package com.yvan.upload.seaweedfs;

import lombok.Cleanup;
import org.apache.commons.lang.StringUtils;
import org.lokra.seaweedfs.core.FileSource;
import org.lokra.seaweedfs.core.FileTemplate;
import org.lokra.seaweedfs.core.file.FileHandleStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author yvan
 */
public class SeaweedFSUtil {
    private static Logger logger = LoggerFactory.getLogger(SeaweedFSUtil.class);

    private static FileTemplate template;
    public static String writeHost;
    public static Integer writePort;
    public static String readHost;
    public static Integer readPort;

    public static void env(String activeDir) {
        if (template != null) {
            return;
        }
        FileSource fileSource = new FileSource();
        try {
            String resourcePath = StringUtils.isBlank(activeDir) ? "seaweedFS_client.properties" : activeDir + File.separatorChar + "seaweedFS_client.properties";
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            Properties properties = new Properties();
            @Cleanup
            InputStream in = loader.getResourceAsStream(resourcePath);
            properties.load(in);

            readHost = properties.getProperty("seaweedFS.readHost");
            readPort = Integer.parseInt(properties.getProperty("seaweedFS.readPort"));

            writeHost = properties.getProperty("seaweedFS.writeHost");
            writePort = Integer.parseInt(properties.getProperty("seaweedFS.writePort"));

            String timeoutStr = properties.getProperty("seaweedFS.timeout");
            int timeout = StringUtils.isBlank(timeoutStr) ? 10000 : Integer.parseInt(timeoutStr);

            // SeaweedFS master服务ip地址
            fileSource.setHost(writeHost);
            // SeaweedFS master服务端口
            fileSource.setPort(writePort);
            fileSource.setConnectionTimeout(timeout);
            fileSource.startup();
            template = new FileTemplate(fileSource.getConnection());
        } catch (IOException e) {
            logger.error("FastDFS Client Init Fail!", e);
        }
    }

    public static FileHandleStatus upload(InputStream inputStream, String filename) throws IOException {
        return template.saveFileByStream(filename, inputStream);
    }

    public static void delete(String fileId) throws IOException {
        template.deleteFile(fileId);
    }
}
